import React from 'react'

export default class extends React.Component {
  constructor(props) {
    super(props)
  }

  //已做或未做任务列表
  doList(list) {
    const {todolist, donelist, onUpdate} = this.props
    let changeList = list === 'todolist' ? todolist : donelist 
    return changeList.map(item => {
      return (
        <li key={item.id} id={item.id} draggable onDragStart={this.dragStart} onDragOver={_ => _.preventDefault()} onDrop={_ => this.dorp(_ , item.do)}>
          <input type="checkbox" checked={!item.do} onChange={_=> onUpdate('changeStatus', item.do, _)}/>
          <p onClick={_ => this.changeVal(_, item.do)}>{item.val}</p>
          <a onClick={_ => onUpdate('del', item.do, _)}>-</a>
        </li>
      )
    })
  }
  // 获取输入的值
  changeVal(e, done) {
    let val = e.target.innerText;
    let ipt = document.createElement('input')
    ipt.value = val
    ipt.id = 'ipt'
    e.target.parentNode.replaceChild(ipt, e.target)
    ipt.select()
    ipt.onblur = function(e) {
    const {onUpdate} = this.props
      let val = e.target.value
      onUpdate('edited', done, e, val)
    }.bind(this)
  }

  // 拖拽
  dragStart(e) {
    const id = e.target.id
    e.dataTransfer.setData('id', id)
  }

  dorp(e, done) {
    const {onUpdate} = this.props
    const id = e.dataTransfer.getData('id')
    onUpdate('drag', done, e, id)
  }
  

  componentDidMount() {
    const {todolist, donelist} = this.props
    console.log(todolist,donelist);
  }

  render() {
    const {todolist, donelist} = this.props
    return (
      <section>
        <h2>正在进行 <span id="todocount">{todolist.length}</span></h2>
        <ol id="todolist" className="demo-box">
          {this.doList('todolist')}
        </ol>
        <h2>已经完成 <span id="donecount">{donelist.length}</span></h2>
        <ul id="donelist">
          {this.doList('donelist')}
        </ul>
		</section>
    )
  }
}